package com.jcl.core.db;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.jcl.core.db.model.DataSourceEnum;
import com.jcl.core.db.model.DbServerEnum;
import com.jcl.core.db.model.InitDataSourceModel;
import com.jcl.core.db.model.ServerCorpEnum;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName InitDataSource
 * @Author yyliu
 * @Date 2018/12/10 16:10
 * @Version 1.0
 **/
public class InitDataSource extends DbServerTools {

    public static Map<Object, Object> targetDataSources(InitDataSourceModel model, String driverClassName) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        Map<String, DataSource> dataSourceMap = getDateSourceMap(model.getDbServerList(), driverClassName);
        for (Map.Entry<String, DataSource> sourceMap : dataSourceMap.entrySet()) {
            targetDataSources.put(sourceMap.getKey(), sourceMap.getValue());
        }
        Map<String, String> corpDbMap = initCorpDbRelation(model.getDbCorpList());
        for (Map.Entry<String, String> sourceMap : corpDbMap.entrySet()) {
            DatabaseContext.setCorpDbNameMap(sourceMap.getKey(), sourceMap.getValue());
        }

        return targetDataSources;
    }

    public static Map<String, String> initCorpDbRelation(List<Map<String, Object>> dbCorpList) {
        Map<String, String> dataMap = new HashMap<>();
        if (null != dbCorpList && dbCorpList.size() > 0) {
            for (Map<String, Object> dbCorp : dbCorpList) {
                dataMap.put(dbCorp.get(ServerCorpEnum.CORP_CODE.getName()).toString(),
                        dbCorp.get(ServerCorpEnum.SERVER_NAME.getName()).toString());
            }
        }
        return dataMap;
    }

    public static Map<String, DataSource> getDateSourceMap(List<Map<String, Object>> dbList, String driverClassName) {

        Map<String, DataSource> dataMap = new HashMap<>();
        if (null != dbList && dbList.size() > 0) {
            for (Map<String, Object> db : dbList) {
                Properties props = new Properties();
                props.put(DataSourceEnum.DRIVER_CLASS_NAME.getName(), driverClassName);
                props.put(DataSourceEnum.DB_URL.getName(), db.get(DbServerEnum.DB_URL.getName()));
                props.put(DataSourceEnum.DB_USERNAME.getName(), db.get(DbServerEnum.DB_USERNAME.getName()));
                props.put(DataSourceEnum.DB_PASSWORD.getName(), db.get(DbServerEnum.DB_PASSWORD.getName()));
                DataSource dataSource = null;
                try {
                    dataSource = DruidDataSourceFactory.createDataSource(props);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                dataMap.put(db.get(DbServerEnum.SERVER_NAME.getName()).toString(), dataSource);
            }
        }
        return dataMap;
    }

}
